home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1994 August / August CD.bin / Shareware / Education / numericalmethods Folder / chap_2 / a2_4.m < prev    next >
Encoding:
Text File  |  1994-06-05  |  2.1 KB  |  88 lines  |  [MATS/MATL]

  1. echo off;
  2. % NUMERICAL METHODS: MATLAB Programs, (c) John H. Mathews 1994
  3. % To accompany the text:
  4. % NUMERICAL METHODS for Mathematics, Science and Engineering, 2nd Ed, 1992
  5. % Prentice Hall, Englewood Cliffs, New Jersey, 07632, U.S.A.
  6. % This free software is complements of the author.
  7.  
  8. % Algorithm 2.4 (Approximate Location of Roots).
  9. % Section    2.3,    Initial Approximations & Convergence Criteria, Page 70
  10. echo on; clc; format long; hold off; clear
  11.  
  12. % To approximately locate the roots of f(x) = 0  over [a,b].
  13.  
  14. %    Define and store f(x) in the M-file  f.m
  15. % function y = f(x)
  16. % y = exp(-x./10) + sin(x);
  17.  
  18. delete f.m
  19. diary f.m; disp('function y = f(x)');...
  20.            disp('y = exp(-x./10) + sin(x);');...
  21. diary off;
  22.  
  23. % Remark. f.m and approot.m are used for Algorithm 2.4
  24. f(0); % Test for file f.m
  25. pause    % Press any key to see the graph y = f(x).
  26.  
  27. clc;
  28. a = 0.0;
  29. b = 30;
  30. c = -1;
  31. d = 2;
  32. n = 100;
  33. h = (b-a)/n;
  34. X = a:h:b;
  35. Y = f(X);
  36. axis([a b c d]);...
  37. plot(X,Y,'-g');...
  38. hold on;...
  39. plot([a b],[0 0],'b',[0 0],[c d],'b');...
  40. xlabel('x');...
  41. ylabel('y');...
  42. title('Graph of y = f(x).');...
  43. grid;...
  44. axis;...
  45. hold off;...
  46. shg; pause    % Press any key to continue.
  47.  
  48. clc;
  49.  
  50. % The abscissas are stored in the vector  X.
  51.  
  52. % The ordinates are stored in the vector  Y.
  53.  
  54. % Place the tolerance for a zero in epsilon.
  55.  
  56. epsilon  = 1e-2;
  57.  
  58. R = approot(X,Y,epsilon);
  59.  
  60. pause    % Press any key to see the approximate root locations.
  61.  
  62. clc; clg;
  63. points = [R;f(R)];
  64. n0 = length(R);
  65. Z0 = zeros(1,n0);
  66. axis([0 30 -1 2]);...
  67. plot(X,Y,'-g',R,Z0,'o');...
  68. hold on;...
  69. plot([a b],[0 0],'b',[0 0],[c d],'b');...
  70. xlabel('x');...
  71. ylabel('y');...
  72. Mx1 = 'Approximate root locations.';...
  73. title(Mx1);...
  74. grid;...
  75. hold off;...
  76. axis;...
  77. shg; pause    % Press any key to continue.
  78.  
  79. Mx1='The search interval is  [';
  80. Mx2='Number of subintervals used is n = ';
  81. Mx3=[Mx1,num2str(a),','num2str(b),'].'];
  82. Mx4=[Mx2,num2str(n)];
  83. Mx5 = 'The approximate root locations are:';
  84. Mx6 = ['     x(k)               f(x(k))'];
  85. clc,echo off, diary output,...
  86. disp(''),disp(Mx3),disp(''),disp(Mx4),disp(''),disp(Mx5),...
  87. disp(''),disp(Mx6),disp(points'),diary off, echo on
  88.